/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Controllers;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author BENSON
 */
public class ControllerReceptionHomepage {

    /**
     * variable and View declarations
     */
    Views.ReceptionHomePage repHome;
    ActionListener actionListener;
    Model.MainModel model;
    Connection conn=null;
    String querry;
    Statement st=null;
    TableRowSorter<TableModel> rowSorter;
    
    /**
     * Default constructor to instantiate the views and methods
     */
    public ControllerReceptionHomepage() {
        repHome = new Views.ReceptionHomePage();
        repHome.setVisible(true);
        model= new Model.MainModel();
        controlCombo(); 
    }
    
    /**
     * creates columns for created tables upon choice from combo box 
     * searches & filters the the table 
     * @param list 
     */
 public void showSelectedOption(Object list){
   if(list.equals("BOOKED APPOINTMENTS")){
    repHome.getTable().setColumnCount(0);
    repHome.getTable().setRowCount(0);
    repHome.getTable().addColumn("Appointment No");
    repHome.getTable().addColumn("Patient No");
    repHome.getTable().addColumn(" Patient Name");
    repHome.getTable().addColumn("Doctor");
    repHome.getTable().addColumn("Patient Report");
    repHome.getTable().addColumn("Appointment Date");
    try{
        
        Class.forName("com.mysql.jdbc.Driver");
        conn =(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/hosiManagerDb?zeroDateTimeBehavior=convertToNull","root","");
        querry="SELECT * FROM Appointments ;" ;
        st=conn.prepareStatement(querry);

        ResultSet rs= st.executeQuery(querry);
   while(rs.next()){
  
   Object[] temp = {rs.getString("appoinmentID"), rs.getString("patientNo"),rs.getString("patientName"),rs.getString("doctor"),
                    rs.getString("doctorReports"),rs.getString("appointmentDate")};
    repHome.getTable().addRow(temp);
    
    rowSorter = new TableRowSorter<>(repHome.getJTable().getModel());
    repHome.getJTable().setRowSorter(rowSorter);
    
    repHome.getSearchField().getDocument().addDocumentListener(new DocumentListener(){
        
            @Override
            public void insertUpdate(DocumentEvent e) {
                String text = repHome.getSearchField().getText();

                if (text.trim().length() == 0) {
                    rowSorter.setRowFilter(null);
                } else {
                    rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                }
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                String text = repHome.getSearchField().getText();
                if (text.trim().length() == 0) {
                    rowSorter.setRowFilter(null);
                } else {
                    rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                }
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                throw new UnsupportedOperationException("Not supported yet."); }

        });
    
   }
   st.close();
   conn.close();
  
    }  
    catch(ClassNotFoundException | SQLException e){
    JOptionPane.showMessageDialog(null,e);
    }
}
   else if(list.equals("PATIENT LIST")){
    repHome.getTable().setColumnCount(0);
    repHome.getTable().setRowCount(0);
    repHome.getTable().addColumn("Patient ID");
    repHome.getTable().addColumn(" Patient Name");
    repHome.getTable().addColumn("Patient Email");
    repHome.getTable().addColumn("Patient PhoneNumber");
    repHome.getTable().addColumn("Emergency Phone");
    repHome.getTable().addColumn("Country ");
    repHome.getTable().addColumn("Gender");
    repHome.getTable().addColumn("Reg Date");
    
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/hosiManagerDb?zeroDateTimeBehavior=convertToNull", "root", "");
            querry = "SELECT * FROM Patients ;";
            st = conn.prepareStatement(querry);

            ResultSet rs = st.executeQuery(querry);
            while (rs.next()) {
                Object[] temp = {rs.getString("patientNo"), rs.getString("patientName"), rs.getString("email"), rs.getString("phoneNO"),
                    rs.getString("emergencyPhoneNO"), rs.getString("country"), rs.getString("gender"), rs.getString("regDate")};
                repHome.getTable().addRow(temp);
                rowSorter = new TableRowSorter<>(repHome.getJTable().getModel());
                repHome.getJTable().setRowSorter(rowSorter);

                repHome.getSearchField().getDocument().addDocumentListener(new DocumentListener(){

            @Override
            public void insertUpdate(DocumentEvent e) {
                String text = repHome.getSearchField().getText();

                if (text.trim().length() == 0) {
                    rowSorter.setRowFilter(null);
                } else {
                    rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                }
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                String text = repHome.getSearchField().getText();

                if (text.trim().length() == 0) {
                    rowSorter.setRowFilter(null);
                } else {
                    rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                }
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

        });
    
            }
            st.close();
            conn.close();

        } catch (ClassNotFoundException | SQLException e) {
            JOptionPane.showMessageDialog(null, e);
        }

}
    
}

   /**
    * Adds an itemListener to the combo box
    */
    public void controlCombo(){
    repHome.getSelectedMenu().addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent arg0) {
            if(arg0.getStateChange() == ItemEvent.SELECTED){
                Object object = ((JComboBox)arg0.getSource()).getSelectedItem();
               showSelectedOption(object);
            }
        }
    });

}

        
        
    /**
     * Method to get source of button clicked using action listener
     * Controls the events of the views
     */
     public void control() {
        actionListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                if (actionEvent.getSource() == repHome.getAddPatientBtn()) {
                    ControllerAddPatient addP = new ControllerAddPatient();
                    addP.control();
                }
                if (actionEvent.getSource() == repHome.getLogoutBtn()) {
                    ControllerMainLogin mainLog = new ControllerMainLogin();
                    repHome.setVisible(false);
                    mainLog.control();
                }
                if (actionEvent.getSource() == repHome.getDeletePatientBtn()) {
                    model.deleteSelectedPatient(repHome);
                }
                if (actionEvent.getSource() == repHome.getModifyPatientBtn()) {
                    model.modifySelectedPatient(repHome);
                }
                if (actionEvent.getSource() == repHome.getBookAppointmentBtn()) {
                    int row = repHome.getJTable().getSelectedRow();
                    Views.BookAppointment book = new Views.BookAppointment();
                    String selected = repHome.getTable().getValueAt(row, 0).toString();
                        if (row >= 0) {
                         ControllerBookAppointment bookApp = new ControllerBookAppointment(repHome.getTable().getValueAt(row, 0).toString(),repHome.getTable().getValueAt(row, 1).toString());
                         bookApp.control();
                        }
                    
                }
                if (actionEvent.getSource() == repHome.getPrintBtn()) {
                    int row = repHome.getJTable().getSelectedRow();
                    Views.BookAppointment book = new Views.BookAppointment();
                    String selected = repHome.getTable().getValueAt(row, 0).toString();
                        if (row >= 0) {
                    ControllerPrintTicket print = new ControllerPrintTicket(selected);
                    print.control();
                        }
                }
            }

        };
        repHome.getAddPatientBtn().addActionListener(actionListener);
        repHome.getLogoutBtn().addActionListener(actionListener);
        repHome.getDeletePatientBtn().addActionListener(actionListener);
        repHome.getModifyPatientBtn().addActionListener(actionListener);
        repHome.getBookAppointmentBtn().addActionListener(actionListener);
        repHome.getPrintBtn().addActionListener(actionListener);
    }

/**
 * Adds actionListener to the text field
 */    
     
public void controlSearch() {
        repHome.getSearchField().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {

            }
        }
        );
  }

}
